﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Comarch.Animation
{
    public static class PanelExtensions
    {
        public static void HideChildrenAndShowPanel(this Panel panel)
        {
            foreach (var item in (IEnumerable<UIElement>)panel.Children) item.Opacity = 0;
            panel.Opacity = 1;
        }

        public static void HideChildrenAndShowItemsControl(this ItemsControl itemsControl)
        {
            var panel = itemsControl.GetItemsPanel();
            if (panel == null) return;

            foreach (var item in (IEnumerable<UIElement>)panel.Children) item.Opacity = 0;
            panel.Opacity = 1;
            itemsControl.Opacity = 1;
        }

        internal static Panel GetItemsPanel(this DependencyObject itemsControl)
        {
            var itemsPresenter = GetVisualChild<ItemsPresenter>(itemsControl);
            if (itemsPresenter == null) return null;

            var itemsPanel = VisualTreeHelper.GetChild(itemsPresenter, 0) as Panel;
            return itemsPanel;
        }

        internal static T GetVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            var child = default(T);
            var numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (var i = 0; i < numVisuals; i++)
            {
                var v = VisualTreeHelper.GetChild(parent, i);
                child = v as T ?? GetVisualChild<T>(v);
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }


        internal static T FindRoot<T>(this DependencyObject child)
             where T : DependencyObject
        {
            var tempPanel = child;
            while (tempPanel != null)
            {
                tempPanel = FindVisualParent<Panel>(tempPanel);
                if (tempPanel != null)
                    child = tempPanel;
            }
            return child as T;
        }

        internal static T FindVisualParent<T>(this DependencyObject child)
            where T : DependencyObject
        {
            var parentObject = VisualTreeHelper.GetParent(child);
            if (parentObject == null) return null;
            var parent = parentObject as T;
            return parent ?? FindVisualParent<T>(parentObject);
        }

        public static Grid GetTopMostParentGrid(this DependencyObject child)
        {
            Grid lastGrid = null;
            DependencyObject parent = VisualTreeHelper.GetParent(child);

            while (parent != null)
            {
                if (parent is Grid)
                    lastGrid = (Grid)parent;

                parent = VisualTreeHelper.GetParent(parent);
            };

            return lastGrid;
        }

    }
}
